package com.mytinyRPC.register.FileServiceRegister;



import com.mytinyRPC.framework.URL;

import java.io.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public  class FileUtil {
    private static Map<String, List<URL>> registerMap = new HashMap<String,List<URL>>(1024);
    public static final String path = "/tmp.txt";

    public static Map<String, List<URL>> getRegisterMap() {
        return registerMap;
    }

    public static void setRegisterMap(Map<String, List<URL>> registerMap) {
        FileUtil.registerMap = registerMap;
    }

    public static String getPath() {
        return path;
    }

    public static void registerService(String interfaceName, URL host) {
        if(registerMap.containsKey(interfaceName)){
            List<URL> list = registerMap.get(interfaceName);
            list.add(host);
        }else {
            List<URL> list = new LinkedList<URL>();
            list.add(host);
            registerMap.put(interfaceName,list);
        }
        try {
            saveFile(path,registerMap);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static List<URL> getURLs(String interfaceName) {
        try {
            registerMap = (Map<String, List<URL>>) readFile(path);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return registerMap.get(interfaceName);
    }
//文件方式存储
    /**
     * 写入文件
     * @param path
     * @param object
     * @throws IOException
     */
    private static void saveFile(String path,Object object) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
        ObjectOutputStream objectOutputStream =new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(object);
    }

    /**
     * 从文件中读取
     * @param path
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private static Object readFile(String path) throws IOException, ClassNotFoundException {
        FileInputStream fileInputStream = new FileInputStream(new File(path));
        ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
        return inputStream.readObject();
    }

}
